<template>
  <el-card shadow="hover" class="mt-20">
    <el-form
      label-width="100px"
      ref="skuFormRef"
      :model="skuFormData"
      :rules="skuFormRules"
    >
      <el-form-item label="SPU名称">
        {{ spuStore.spu.spuName }}
      </el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input placeholder="SKU名称" v-model="skuFormData.skuName" />
      </el-form-item>
      <el-form-item label="价格(元)" prop="price">
        <el-input-number
          class="sku__input-number"
          placeholder="价格(元)"
          controls-position="right"
          :min="0"
          v-model="skuFormData.price"
        />
      </el-form-item>
      <el-form-item label="重量(千克)" prop="weight">
        <el-input-number
          class="sku__input-number"
          placeholder="重量(千克)"
          controls-position="right"
          :min="0"
          v-model="skuFormData.weight"
        />
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          placeholder="规格描述"
          type="textarea"
          :rows="3"
          v-model="skuFormData.skuDesc"
        />
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row :gutter="10" class="sku__row">
          <el-col
            v-for="(attr, index) in attrList"
            :key="attr.id"
            :xs="24"
            :sm="12"
            :lg="8"
            :xl="4"
          >
            <div class="sku__col-wrap">
              <span class="sku__col-title">{{ attr.attrName }}</span>
              <el-select v-model="skuFormData.skuAttrValueList[index]">
                <el-option
                  v-for="attrValue in attr.attrValueList"
                  :key="attrValue.id"
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                  :label="attrValue.valueName"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row :gutter="10" class="sku__row">
          <el-col
            v-for="(spuSaleAttr, index) in spuSaleAttrList"
            :key="spuSaleAttr.id"
            :xs="24"
            :sm="12"
            :lg="8"
            :xl="4"
          >
            <div class="sku__col-wrap">
              <span class="sku__col-title">{{ spuSaleAttr.saleAttrName }}</span>
              <el-select v-model="skuFormData.skuSaleAttrValueList[index]">
                <el-option
                  v-for="spuSaleAttrValue in spuSaleAttr.spuSaleAttrValueList"
                  :key="spuSaleAttrValue.id"
                  :value="`${spuSaleAttr.id}:${spuSaleAttr.saleAttrName}:${spuSaleAttrValue.id}:${spuSaleAttrValue.saleAttrValueName}`"
                  :label="spuSaleAttrValue.saleAttrValueName"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          :data="spuImageList"
          border
          @selection-change="handleSelection"
        >
          <el-table-column type="selection" width="60" align="center" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img :src="row.imgUrl" :alt="row.imgName" class="sku__img" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-tag type="success" v-if="row.isDefault === '1'"
                >默认图片</el-tag
              >
              <el-button
                type="primary"
                size="small"
                v-else
                @click="handleDefaultImg(row)"
                >设置默认图片</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AddSku",
};
</script>

<script lang="ts" setup>
import { onMounted, ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { GetAttrInfoListApi } from "@/api/product/attr";
import { GetSpuImgListApi, GetSpuSaleAttrListApi } from "@/api/product/spu";
import { AddOrUpdateSkuApi } from "@/api/product/sku";
import { useSpuStore } from "@/stores/spu";
import { useCategoryStore } from "@/stores/category";
import type { AttrList } from "@/api/product/model/attrModel";
import type {
  SpuSaleAttrList,
  SpuImageList,
} from "@/api/product/model/spuModel";
import type {
  SkuImgList,
  SkuImgItem,
  SkuFormData,
} from "@/api/product/model/skuModel";

const emit = defineEmits(["setShowSpuList"]);
// 点击取消按钮触发的回调，返回SpuList
const handleCancel = () => {
  emit("setShowSpuList", 1);
};

const attrList = ref<AttrList>([]);

const spuSaleAttrList = ref<SpuSaleAttrList>([]);

const spuImageList = ref<SpuImageList>([]);

const categoryStore = useCategoryStore();
onMounted(async () => {
  attrList.value = await GetAttrInfoListApi({
    category1Id: categoryStore.category1Id as number,
    category2Id: categoryStore.category2Id as number,
    category3Id: categoryStore.category3Id as number,
  });
});

const spuStore = useSpuStore();
onMounted(async () => {
  spuSaleAttrList.value = await GetSpuSaleAttrListApi(
    spuStore.spu.id as number
  );
});

onMounted(async () => {
  spuImageList.value = await GetSpuImgListApi(spuStore.spu.id as number);
});

// 自定义图片校验规则
const skuImgListValidator = (rule: any, value: SkuImgList, callback: any) => {
  // 1. 至少选择一张图片
  if (!value.length) {
    callback(new Error("请至少选择一张图片！"));
    return;
  }
  // 2. 选中的图片必须有默认图片
  if (!value.some((img) => img.isDefault === "1")) {
    callback(new Error("选中的图片必须有默认图片"));
    return;
  }

  // 校验成功
  callback();
};

const skuFormRef = ref();
const skuFormData = reactive<SkuFormData>({
  skuName: "",
  price: undefined,
  weight: undefined,
  skuDesc: "",
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuDefaultImg: "",
  skuImageList: [],
});
const skuFormRules = reactive({
  skuName: [
    {
      required: true,
      message: "请输入SKU名称",
      trigger: "blur",
    },
  ],
  price: [
    {
      required: true,
      message: "请输入SKU价格",
      trigger: "blur",
    },
  ],
  weight: [
    {
      required: true,
      message: "请输入SKU重量",
      trigger: "blur",
    },
  ],
  skuDesc: [
    {
      required: true,
      message: "请输入SKU规格描述",
      trigger: "blur",
    },
  ],
  skuAttrValueList: [
    {
      required: true,
      message: "请选择SKU平台属性",
      trigger: "change",
    },
  ],
  skuSaleAttrValueList: [
    {
      required: true,
      message: "请选择SKU销售属性",
      trigger: "change",
    },
  ],
  skuImageList: [
    // { required: true, message: "请选择SKU图片列表", trigger: "change" },
    {
      required: true,
      validator: skuImgListValidator,
    },
  ],
});

const handleSelection = (val: SkuImgList) => {
  skuFormData.skuImageList = val;
};

// 点击设置默认图片的回调
const handleDefaultImg = (row: SkuImgItem) => {
  // 排他
  spuImageList.value.forEach((img) => (img.isDefault = "0"));
  // 将点击改为1
  row.isDefault = "1";
  // 更新默认图片地址
  skuFormData.skuDefaultImg = row.imgUrl;

  // 判断点击图片是否选中，选中了就要清空表单校验错误信息
  if (skuFormData.skuImageList.some((img) => img === row)) {
    skuFormRef.value.clearValidate(["skuImageList"]);
  }
};

// 点击保存触发的回调
const handleSubmit = async () => {
  // 完成表单校验
  await skuFormRef.value.validate();
  await AddOrUpdateSkuApi({
    ...skuFormData,
    category3Id: categoryStore.category3Id as number,
    spuId: spuStore.spu.id as number,
    // 组件收集的数据 [undefined, string]
    // 发送请求需要的数据是对象，将undefined过滤，格式化成对象
    skuAttrValueList: skuFormData.skuAttrValueList
      .filter(Boolean)
      .map((attr) => {
        const [attrId, attrName, valueId, valueName] = (attr as string).split(
          ":"
        );
        return {
          attrId: +attrId,
          attrName,
          valueId: +valueId,
          valueName,
        };
      }),
    skuSaleAttrValueList: skuFormData.skuSaleAttrValueList
      .filter(Boolean)
      .map((attr) => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = (
          attr as string
        ).split(":");
        return {
          saleAttrId: +saleAttrId,
          saleAttrName,
          saleAttrValueId: +saleAttrValueId,
          saleAttrValueName,
        };
      }),
  });
  ElMessage.success("添加SKU成功");
  handleCancel();
};
</script>

<style scoped>
.sku__input-number {
  width: 100%;
}

:deep(.el-input__inner) {
  text-align: left;
}

.sku__col-wrap {
  display: flex;
  margin-bottom: 10px;
}

.sku__col-title {
  flex-grow: 1;
  margin-right: 10px;
  text-align: right;
}

.sku__row {
  width: 100%;
}

.sku__img {
  width: 100px;
  height: 100px;
}
</style>
